<template>
	<view :style="viewColor">
		<view class='my-order' >
			<view class="order-position">
				<navigator class="search acea-row row-middle" url="/pages/users/order_list/search" hover-class="none">
					<text class="iconfont icon-ic_search"></text>
					搜索我的订单
				</navigator>
				<view class='nav acea-row row-around'>
					<view class='item' :class='orderStatus == -1 ? "on" : ""' @click="statusClick(-1)">
						<view>全部</view>
						<!-- <view class='num'>{{orderData.all || 0}}</view> -->
					</view>
					<view class='item' :class='orderStatus == 0 ? "on" : ""' @click="statusClick(0)">
						<view>待付款</view>
						<!-- <view class='num'>{{orderData.noPay || 0}}</view> -->
					</view>
					<view class='item' :class='orderStatus == 1 ? "on" : ""' @click="statusClick(1)">
						<view>待核销</view>
						<!-- <view class='num'>{{orderData.noPostage || 0}}</view> -->
					</view>
					<view class='item' :class='orderStatus == 2 ? "on" : ""' @click="statusClick(3)">
						<view>待评价</view>
						<!-- <view class='num'>{{orderData.noComment || 0}}</view> -->
					</view>
					<view class='item' :class='orderStatus == 4 ? "on" : ""' @click="statusClick(4)">
						<view>售后</view>
						<!-- <view class='num'>{{orderData.noComment || 0}}</view> -->
					</view>
				</view>
				<view class='list'>
					<view class='item' v-for="(item, index) in orderList" :key="index">
						<view @click='goOrderDetails(item.id)'>
							<view class='title acea-row row-between-wrapper'>
								<view class="acea-row row-middle left-wrapper" @click.stop="goMall(item)">
									<text class="iconfont icon-ic_mall"></text>
									<view class="store-name">{{ item.merchant.mer_name }}</view>
									<text class="iconfont icon-ic_rightarrow">订单号：{{ item.order_sn }}</text>
								</view>
								<view v-if="item.status == 0" class='t-color'>
									<text>待支付</text>
								</view>
								<view v-if="item.status == 1" class='t-color'>待核销</view>
								<view v-if="item.status == 3" class='t-color'>待评价</view>
								<view v-if="item.status == 4" class='t-color'>已完成</view>
								<view v-if="item.status == -2" class='t-color'>已退款</view>
							</view>
							<view>
								<view class='item-info acea-row row-between row-top' >
									<view class='pictrue'>
										<image :src=" item.product.image[0]"
											style="width: 100%; height: 100%; border-radius: 16rpx;" />
									</view>
									<view class='text acea-row row-between'>
										<view class='name'>
											<view class='product-title'
												style="font-size: 28rpx; color: #222; font-weight: 500; margin-bottom: 8rpx;">
												{{ item.product.title }}
											</view>
											<view class='name' :class="item.status === 0 ? 'line1' : 'line2'">
												<text class="event_name event_bg">入住时间</text><text></text>

											</view>
											<view class="t-color refund-text">
												{{ item.booking_date }}
											</view>
										</view>
										<view class='money'>
											<view class="regular">
												{{ item.booking_date_start }}至{{ item.booking_date_end }}
											</view>
										</view>
									</view>
								</view>
							</view>
							<view class='totalPrice acea-row row-right'>
								金额
								<view class='money p-color'>
									<priceFormat :price="item.price" weight intSize="32" floatSize="22" labelSize="22">
									</priceFormat>
								</view>
							</view>

						</view>
						<view class='bottom acea-row row-right row-middle'>
							<!-- <view
								v-if="!item.receipt && item.status != -1 && item.open_receipt == 1 && item.order_type!==1"
								class='bnt cancelBnt' @click.stop='applyInvoice(item.order_id)'>申请开票</view> -->
							<block v-if="item.status == 0 || item.status == 9 || item.status == -1">
								<view class='bnt b-color' @click='goOrderDetails(item.id)'>查看详情</view>
							</block>
							<block v-if="item.status == 1">
								<view class='bnt b-color' @tap='confirmOrder(item, index)'>去核销</view>
							</block>
							<block v-if="item.status == 2">

								<view class='bnt b-color' @click='goOrderEvaluation(item.id)'>去评价</view>
							</block>
							<block v-if="item.status == 3">
								<view class='bnt b-color' @click='goOrderDetails(item.id)'>
									查看详情</view>
							</block>
						</view>
					</view>
				</view>
				<view class='loadingicon acea-row row-center-wrapper' v-if="orderList.length > 5">
					<text class='loading iconfont icon-jiazai' :hidden='loading == false'></text>{{ loadTitle }}
				</view>
				<view v-if="orderList.length == 0 && page > 1">
					<emptyPage title="暂无订单~" :noImage="`${domain}/static/images/noRecord.png`"></emptyPage>
				</view>
			</view>
		</view>
		<home></home>
		<addInvoicing ref="addInvoicing" @changeInvoiceClose="changeInvoiceClose" :invoice='invoice'></addInvoicing>
		<uni-popup ref="verifyPopup" type="center" :maskClick="true" @change="onVerifyPopupChange">
			<view class="verify-popup-content">
				<view @click="closeVerifyPopup" class="close-btn">
					<text class="iconfont icon-ic_close"></text>
				</view>
				<view class="popup-title">
					核销二维码</view>
				<view class="title-underline">
				</view>
				<image :src="verifyCodeImg" class="qrcode-image" mode="aspectFit"></image>
				<view class="verify-code-label">核销码</view>
				<view class="verify-code-value">
					{{ verifyCode }}
				</view>
			</view>
		</uni-popup>
	</view>
</template>
<script>
	// +----------------------------------------------------------------------
	// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
	// +----------------------------------------------------------------------
	// | Copyright (c) 2016~2024 https://www.crmeb.com All rights reserved.
	// +----------------------------------------------------------------------
	// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
	// +----------------------------------------------------------------------
	// | Author: CRMEB Team <admin@crmeb.com>
	// +----------------------------------------------------------------------
	import {
		getRoomOrderList,
		roomorderData,
		roomorderTake,
		applyInvoiceApi,
		getOrderPayTypeList
	} from '@/api/order.js';
	import {
		openOrderSubscribe
	} from '@/utils/SubscribeMessage.js';
	import payment from '@/components/payment';
	import home from '@/components/home/index.vue';
	import addInvoicing from '@/components/addInvoicing';
	import {
		mapGetters
	} from "vuex";
	import emptyPage from '@/components/emptyPage.vue';
	import {
		configMap
	} from '@/utils'
	import {
		HTTP_REQUEST_URL
	} from '@/config/app';
	import {
		toLogin
	} from '@/libs/login.js';
	import zbCode from '@/components/zb-code/zb-code.vue'
	import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue'
	export default {
		components: {
			payment,
			emptyPage,
			home,
			addInvoicing,
			zbCode,
			uniPopup
		},
		data() {
			return {
				loading: false, //是否加载中
				loadend: false, //是否加载完毕
				loadTitle: '加载更多', //提示语
				orderList: [], //订单数组
				presellProList: [], //定金预售订单
				presellOrderCount: 0,
				orderData: {}, //订单详细统计
				orderStatus: 0, //订单状态
				page: 1,
				limit: 20,
				domain: HTTP_REQUEST_URL,
				payMode: [],
				pay_close: false,
				pay_order_id: '',
				invoice_order_id: '',
				totalPrice: '0',
				isReady: true,
				invoice: {
					invoice: false,
					add: false,
				},
				showVerifyPopup: false, // 控制核销弹窗显示
				verifyCode: '', // 当前核销码
				verifyOrderId: '', // 当前核销订单ID
				verifyCodeImg: ''
			};
		},
		computed: {
			...mapGetters(['isLogin', 'viewColor', 'orderPayList']),
			...configMap(['hide_mer_status', 'community_status']),
		},
		watch: {
			orderPayList: {
				handler(nVal, oVal) {
					if (nVal) {
						this.payMode = nVal;
					}
				},
				immediate: true,
				deep: true
			}
		},
		onShow() {
			if (this.isLogin) {
				this.page = 1;
				this.loadend = false;
				this.loading = false;
				this.pay_close = false;
				// 确保弹窗不会自动显示
				this.showVerifyPopup = false;
				if (this.$refs.verifyPopup) {
					this.$refs.verifyPopup.close();
				}
				this.getRoomOrderData();
				this.getRoomOrderList();
			} else {
				toLogin()
			}
		},
		onReady() {},
		mounted: function() {},
		methods: {
			goOrderDetails(id){
				uni.navigateTo({
					url:'/pages/users/roomorder-detail/roomorder-detail?id='+id
				})
			},
			// 跳转到评价页面
			goOrderEvaluation(orderId) {
				uni.navigateTo({
					url: '/pages/users/evaluation/evaluation?orderId=' + orderId
				})
			},
			goBack: function() {
				uni.navigateBack({
					delta: 1,
					fail: () => {
						// 如果无法返回，则跳转到用户中心
						uni.switchTab({
							url: '/pages/user/index'
						})
					}
				})
			},
			// 去商铺
			goMall(item) {
				if (this.hide_mer_status == 0) {
					uni.navigateTo({
						url: '/pages/store/home/index?id=' + item.mer_id
					})
				}
			},
			/**
			 * 事件回调
			 *
			 */
			onChangeFun: function(e) {
				let opt = e;
				let action = opt.action || null;
				let value = opt.value != undefined ? opt.value : null;
				(action && this[action]) && this[action](value);
			},
			/**
			 * 关闭支付组件
			 *
			 */
			payClose: function() {
				this.pay_close = false;
			},
			/**
			 * 生命周期函数--监听页面加载
			 */
			onLoad: function(options) {
				if (options.status) this.orderStatus = options.status;
				// 确保不会自动显示核销弹窗
				this.showVerifyPopup = false;
			},
			/**
			 * 获取订单统计数据
			 *
			 */
			getRoomOrderData: function() {
				let that = this;
				roomorderData().then(res => {
					that.$set(that, 'orderData', res.data);
				})
			},
			/**
			 * 打开支付组件
			 *
			 */
			goPay: function(pay_price, order_id) {
				this.order_id = order_id;
				this.pay_order_id = order_id.toString();
				this.$set(this, 'totalPrice', pay_price);
				this.$util.getPayTypeList(this.pay_order_id, 0);
				this.$set(this, 'pay_close', true);
			},
			/**
			 * 支付成功回调
			 *
			 */
			pay_complete: function() {
				this.loadend = false;
				this.page = 1;
				this.$set(this, 'orderList', []);
				this.pay_close = false;
				this.pay_order_id = '';
				this.getRoomOrderData();
				this.getRoomOrderList();
			},
			/**
			 * 支付失败回调
			 *
			 */
			pay_fail: function() {
				this.pay_close = false;
				this.pay_order_id = '';
			},
			/**
			 * 去订单详情
			 */
			goRoomOrderDetails: function(order_id) {
				let self = this
				if (!order_id) return that.$util.Tips({
					title: '缺少订单号无法查看订单详情'
				});
				// #ifdef MP
				uni.showLoading({
					title: '正在加载',
				})
				openOrderSubscribe().then(() => {
					uni.hideLoading();
					if (self.orderStatus == 0) {
						uni.navigateTo({
							url: '/pages/order_details/stay?order_id=' + order_id
						})
					} else {
						uni.navigateTo({
							url: '/pages/order_details/index?order_id=' + order_id
						})
					}
				}).catch(() => {
					uni.hideLoading();
				})
				// #endif
				// #ifndef MP
				if (self.orderStatus == 0) {
					uni.navigateTo({
						url: '/pages/order_details/stay?order_id=' + order_id
					})
				} else {
					uni.navigateTo({
						url: '/pages/order_details/index?order_id=' + order_id
					})
				}
				// #endif
			},
			/**
			 * 点击去评价
			 */
			goRoomOrderDetails_Evaluation: function(order_id) {
				let self = this
				if (!order_id) return that.$util.Tips({
					title: '缺少订单号无法查看订单详情和评价'
				});
				uni.navigateTo({
					url: '/pages/order_details/index?order_id=' + order_id
				})
			},
			/**
			 * 切换类型
			 */
			statusClick: function(status) {
				if (status == this.orderStatus) return;
				this.orderStatus = status;
				this.loadend = false;
				this.loading = false;
				this.page = 1;
				this.$set(this, 'orderList', []);
				this.getRoomOrderList();
			},
			/**
			 * 获取订单列表
			 */
			getRoomOrderList: function() {
				let that = this;
				if (that.loadend) return;
				if (that.loading) return;
				that.loading = true;
				that.loadTitle = "加载更多";
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				getRoomOrderList({
					status: that.orderStatus - 1,
					page: that.page,
					limit: that.limit,
				}).then(res => {

					uni.hideLoading()
					let list = res.data.list || [];
					let loadend = list.length < that.limit;
					that.orderList = that.page == 1 ? list : that.$util.SplitArray(list, that.orderList);
					that.$set(that, 'orderList', that.orderList);
					that.loadend = loadend;
					that.loading = false;
					that.loadTitle = loadend ? "我也是有底线的" : '加载更多';
					that.page = that.page + 1;
					that.isReady = true;
					console.log(that.orderList, '123123')
				}).catch(err => {
					that.loading = false;
					that.loadTitle = "加载更多";
				})
			},

			// 确认收货
			confirmOrder: function(item, index) {
				console.log(item, index)
				// 弹出二维码+核销码弹窗
				this.verifyOrderId = item.order_id;
				this.verifyCode = item.verify_code || item.order_sn || '';
				this.verifyCodeImg = item.verify_code_img
				
				// 使用 $nextTick 确保组件完全加载后再操作
				this.$nextTick(() => {
					if (this.$refs.verifyPopup) {
						this.$refs.verifyPopup.open();
					} else {
						console.error('核销弹窗组件未找到');
						// 降级处理：显示简单的提示
						uni.showModal({
							title: '核销信息',
							content: `核销码：${this.verifyCode}`,
							showCancel: false
						});
					}
				});
			},
			closeVerifyPopup() {
				// 安全检查组件引用是否存在
				if (this.$refs.verifyPopup) {
					this.$refs.verifyPopup.close();
				} else {
					console.error('核销弹窗组件未找到');
				}
			},
			onVerifyPopupChange(e) {
				this.showVerifyPopup = e.show;
			},
			/*申请开票*/
			applyInvoice(order_id) {
				let that = this;
				that.invoice_order_id = order_id
				that.invoice.invoice = true;
				that.$refs.addInvoicing.popupTitle = false;
				that.$refs.addInvoicing.getInvoiceDefault();
				that.$refs.addInvoicing.getInvoiceList();
			},
			// 关闭发票弹窗
			changeInvoiceClose: function(data) {
				if (data) this.getInvoiceData(data);
				this.$set(this.invoice, 'invoice', false);
			},
			// 开票回调
			getInvoiceData(data) {
				let that = this
				applyInvoiceApi(that.invoice_order_id, data).then(res => {
					that.loadend = false;
					that.loading = false;
					that.page = that.page - 1;
					that.getRoomOrderList();
					return that.$util.Tips({
						title: res.message,
					});
				}).catch(err => {
					return that.$util.Tips({
						title: err
					});
				})
			}
		},
		onReachBottom: function() {
			this.getRoomOrderList();
		}
	}
</script>

<style scoped lang="scss">
	.t-color {
		color: var(--view-theme);
	}

	.p-color {
		color: var(--view-priceColor);
	}

	.b-color {
		background-color: var(--view-theme);
	}

	.my-order .order-position {
		position: relative;
		margin-top: 20rpx;
		padding: 20rpx 0;
		padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	}

	.my-order .nav {
		background-color: #fff;
		width: 690rpx;
		// height: 140rpx;
		border-radius: 24rpx;
		margin: 20rpx auto 0 auto;
	}

	.my-order .nav .item {
		text-align: center;
		font-size: 26rpx;
		color: #282828;
		padding: 29rpx 0;
		// height: 140rpx;
	}

	.my-order .nav .item.on {
		font-weight: bold;
		border-bottom: 5rpx solid var(--view-theme);
	}

	.my-order .nav .item .num {
		margin-top: 18rpx;
	}

	.my-order .list {
		width: 690rpx;
		margin: 20rpx auto 0 auto;
	}

	.my-order .list .item {
		background-color: #fff;
		border-radius: 24rpx;
		margin-bottom: 20rpx;
	}

	.my-order .list .item .title {
		height: 84rpx;
		padding: 0 30rpx;
		font-size: 28rpx;
		color: #282828;

		.left-wrapper {
			.iconfont {
				font-size: 28rpx;
			}

			.store-name {
				margin: 0 10rpx;
			}

			.icon-ic_rightarrow {
				font-size: 20rpx;
			}
		}
	}

	.my-order .list .item .title .sign {
		font-size: 24rpx;
		padding: 0 7rpx;
		height: 36rpx;
		margin-right: 15rpx;
	}

	.my-order .list .item .item-info {
		padding: 0 30rpx;
		margin-top: 22rpx;
	}

	.my-order .list .item .item-info .pictrue {
		width: 120rpx;
		height: 120rpx;
		border-radius: 16rpx;
	}

	.my-order .list .item .item-info .pictrue image {
		width: 100%;
		height: 100%;
		border-radius: 16rpx;
	}

	.my-order .list .item .item-info .text {
		width: 486rpx;
		font-size: 28rpx;
		color: #999;
		margin-top: 6rpx;
	}

	.my-order .list .item .item-info .text .name {
		width: 320rpx;
		color: #282828;
	}

	.my-order .list .item .item-info .refund-text {
		margin-top: 10rpx;
		font-size: 22rpx;
	}

	.my-order .list .item .item-info .text .name .font_bg-red {
		position: relative;
		top: -2px;
	}

	.event_bg {
		background: #FF7F00;
	}

	.event_color {
		color: #FF7F00;
	}

	.my-order .list .item .event_name {
		display: inline-block;
		margin-right: 9rpx;
		color: #fff;
		font-size: 20rpx;
		padding: 0 8rpx;
		line-height: 30rpx;
		text-align: center;
		border-radius: 6rpx;
	}

	.my-order .list .item .event_ship {
		font-size: 20rpx;
		margin-top: 10rpx;
	}

	.my-order .list .event_price {
		margin: 0 0 50rpx 120rpx;
	}

	.my-order .list .item .item-info .text .money {
		text-align: right;
	}

	.my-order .list .item .totalPrice {
		font-size: 26rpx;
		color: #282828;
		text-align: right;
		margin: 27rpx 0 0 30rpx;
		padding: 0 30rpx 30rpx 0;
	}

	.my-order .list .item .totalPrice .money {
		font-size: 28rpx;
		margin-left: 6rpx;
	}

	.my-order .list .item .bottom {
		height: 107rpx;
		padding-right: 30rpx;
		margin-left: 30rpx;
	}

	.my-order .list .item .bottom .bnt {
		width: 176rpx;
		height: 64rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #fff;
		border-radius: 50rpx;
		font-size: 27rpx;
		font-size: 24rpx;
	}

	.my-order .list .item .bottom .bnt.cancelBnt {
		border: 1px solid #ddd;
		color: #666666;
	}

	.my-order .list .item .bottom .bnt.colorBnt {
		border: 1px solid var(--view-theme);
		color: var(--view-theme);
	}

	.my-order .list .item .bottom .bnt .icon-ic_edit {
		font-size: 26rpx;
		margin-right: 10rpx;
	}

	.my-order .list .item .bottom .bnt~.bnt {
		margin-left: 17rpx;
	}

	.noCart {
		margin-top: 171rpx;
		padding-top: 0.1rpx;
	}

	.noCart .pictrue {
		width: 414rpx;
		height: 336rpx;
		margin: 78rpx auto 56rpx auto;
	}

	.noCart .pictrue image {
		width: 100%;
		height: 100%;
	}

	.event_container {
		width: 690rpx;
		background-size: cover;
		background-repeat: no-repeat;
		margin: 20rpx auto;
		padding: 30rpx 30rpx 24rpx;
		border-radius: 16rpx;

		.info {
			width: 420rpx;

			.title {
				color: #282828;
				font-size: 26rpx;
				font-weight: 500;
			}

			.desc {
				color: #999;
				font-size: 24rpx;
				margin-top: 16rpx;
			}
		}

		.photo {
			width: 144rpx;

			.picture {
				width: 76rpx;
				height: 76rpx;

				image {
					width: 100%;
					height: 100%;
					border-radius: 8rpx;
				}
			}

			.more_btn {
				color: #fff;
				background: #F97E3B;
				width: 40rpx;
				height: 40rpx;
				border-radius: 40rpx;
				text-align: center;
				position: relative;
				top: 18rpx;

				text {
					font-size: 20rpx;
				}
			}
		}
	}

	.search {
		height: 70rpx;
		padding: 0 30rpx;
		border-radius: 35rpx;
		margin: -35rpx 30rpx 0;
		background-color: #FFFFFF;
		font-size: 26rpx;
		color: #999999;

		.iconfont {
			margin-right: 10rpx;
			font-size: 23rpx;
		}
	}

	/* 核销二维码弹窗样式 */
	.verify-popup-content {
		width: calc(100vw - 40px); /* 屏幕宽度减去左右各20px边距 */
		max-width: 600rpx; /* 最大宽度限制 */
		margin: 0 20px; /* 左右20px边距 */
		padding: 48rpx 36rpx;
		background: #fff;
		border-radius: 20rpx;
		text-align: center;
		box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.10);
		position: relative;
		box-sizing: border-box;
	}

	.close-btn {
		position: absolute;
		top: 24rpx;
		right: 24rpx;
		width: 56rpx;
		height: 56rpx;
		border-radius: 50%;
		background: rgba(0,0,0,0.06);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 2;
		cursor: pointer;

		.iconfont {
			font-size: 36rpx;
			color: #888;
		}
	}

	.popup-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #222;
		margin-bottom: 18rpx;
		letter-spacing: 2rpx;
	}

	.title-underline {
		width: 60rpx;
		height: 6rpx;
		background: linear-gradient(90deg, #ffb86c 0%, #ff7f50 100%);
		border-radius: 3rpx;
		margin: 0 auto 36rpx auto;
	}

	.qrcode-image {
		width: #{"min(220rpx, calc(100vw - 160px))"}; /* 适配屏幕宽度，最小保持160px边距 */
		height: #{"min(220rpx, calc(100vw - 160px))"};
		max-width: 300rpx; /* 最大尺寸限制 */
		max-height: 300rpx;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 16rpx rgba(255,127,80,0.10);
		background: #f8f8f8;
		margin-bottom: 32rpx;
		display: inline-block;
	}

	.verify-code-label {
		margin-bottom: 12rpx;
		font-size: 28rpx;
		color: #888;
	}

	.verify-code-value {
		font-size: 40rpx;
		font-weight: bold;
		color: #ff7f50;
		letter-spacing: 2rpx;
		margin-bottom: 36rpx;
		word-break: break-all; /* 防止长核销码溢出 */
	}
</style>